import axios from 'axios'
import { getToken } from '@/utils/auth'
import store from '../store'
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 15000 // 请求超时时间
})
//创建request拦截器:
service.interceptors.request.use(config=>{
    //从cookie中获得tooken:
    //alert(process.env.NODE_ENV)
   // alert(process.env.BASE_API)
    if (store.getters.token) {
        config.headers['Authorization'] = getToken() // 让每个请求携带自定义token
    }
    return config
}),error=>{
    console.log(error)
    Promise.reject(error)
}

//创建response拦截器:

service.interceptors.response.use(response=>{
    const res = response.data;
    if(res.code !== 200) {
        console.log(res.message);

        if (res.code === 401 || res.code === 403) {
            //清除cookie:
            store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
            })
            return Promise.reject('error')
        }
        if(res.code ===500){
            store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
            })
            return Promise.reject('error')
        }
    }else{
        //code 200:
        return response.data;
    }
},error => {
    console.log('err' + error)// for debug
    alert(error.message);
    return Promise.reject(error);
})
export  default  service;

